package com.niiwoo.civet.mobile.lanmao.handler;/**
 * Created by DELL on 2017/12/7.
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.service.AccountFundTransferDubboService;
import com.niiwoo.tripod.lanmao.enums.LanMaoDirectServiceNameEnum;
import com.niiwoo.tripod.lanmao.response.GroupAccountTransferReponse;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 资金划拨异步回调通知处理类
 *
 * @author xiaoyingping
 * @create 2017-12-16 14:59
 **/
@Component
@Slf4j
public class AccountFundTransferNotifyHandler implements LanMaoNotifyHandler {

    @Reference(version = "1.0.0")
    private AccountFundTransferDubboService accountFundTransferDubboService;

    @Override
    public boolean supports(String serviceName) {
        return LanMaoDirectServiceNameEnum.GROUP_ACCOUNT_TRANSFER.name().equals(serviceName);
    }

    @Override
    public HandleResult handle(JSONObject json) {
        HandleResult result = new HandleResult();
        if (json == null) {
            log.error("账户资金划拨，回调Handler:null");
        }

        String jsonStr = json.toJSONString();
        log.info("账户资金划拨，回调Handler:{}", jsonStr);

        GroupAccountTransferReponse response = JSON.parseObject(jsonStr, GroupAccountTransferReponse.class);
        if (Objects.nonNull(response)) {
            result.setRequestNo(response.getRequestNo());

            try {
                if (response.isSuccess()) {
                    //划拨成功
                    accountFundTransferDubboService.processSubmitFundTransferNotify(response.getRequestNo(), true);
                } else {
                    //划拨失败
                    accountFundTransferDubboService.processSubmitFundTransferNotify(response.getRequestNo(), false);
                }

                result.setNeedAck(true);
                log.info("账户资金划拨，回调处理成功###data={}", JSON.toJSONString(result));
            } catch (BizException e) {
                log.error("账户资金划拨，回调处理失败BizException:, Handler:{}", jsonStr);
                log.error("账户资金划拨，回调处理失败BizException", e);
                throw e;
            } catch (Exception e) {
                log.error("账户资金划拨，回调处理失败Exception:, Handler:{}", jsonStr);
                log.error("账户资金划拨，回调处理失败Exception", e);
                throw new BizException();
            }
        }

        return result;
    }
}
